from django.http import HttpResponse
from django.shortcuts import render, redirect

from app01 import models
from app01.utils.pagination import Pagination
from app01.utils.form import CityModelForm


def city_list(request):
    """ 城市列表 """
    title = "城市列表"
    queryset = models.City.objects.all().order_by('-id')
    form = CityModelForm()
    page_object = Pagination(request, queryset)
    context = {
        "title": title,
        "form": form,
        "queryset": page_object.page_queryset,  # 分完页数据
        "page_string": page_object.html(),  # 页码
    }
    return render(request, "city_list.html", context)


def city_add(request):
    """ 添加城市 """
    title = "添加城市"
    if request.method == "GET":
        form = CityModelForm()
        return render(request, 'city_add.html', {'form': form, 'title': title})
    form = CityModelForm(data=request.POST, files=request.FILES)
    if form.is_valid():
        form.save()
        return redirect("/city/list/")
    return render(request, 'city_add.html', {'form': form, 'title': title})


def city_edit(request,nid):
    ...


def city_delete(request,nid):
    models.City.objects.filter(id=nid).delete()
    return redirect("/city/list/")
